/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?
    lazy var coreDataStack = CoreDataStack.share

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Device")
    do {
        let results = try coreDataStack.managedObjectContext.fetch(fetchRequest)
      if results.count == 0 {
        addTestData()
      }
    } catch {
      fatalError("Error fetching data!")
    }

    if let tab = window?.rootViewController as? UITabBarController {
      for child in tab.viewControllers ?? [] {
        if  let child = child as? UINavigationController,
            let top = child.topViewController as? DevicesTableViewController {
            top.coreDataStack = self.coreDataStack;
//            if top.responds(to: Selector(("setCoreDataStack:"))) {
//                top.perform(Selector(("setCoreDataStack")), with: self.coreDataStack, afterDelay: 0)
//          }
        }
      }
    }

    return true
  }

  func addTestData() {
    guard let entity = NSEntityDescription.entity(forEntityName: "Device", in: coreDataStack.managedObjectContext),
        let personEntity = NSEntityDescription.entity(forEntityName: "Person", in: coreDataStack.managedObjectContext),
        let deviceTypeEntity = NSEntityDescription.entity(forEntityName: "DeviceType", in: coreDataStack.managedObjectContext) else {
      fatalError("Could not find entity descriptions!")
    }

    let phoneDeviceType = DeviceType(entity: deviceTypeEntity, insertInto: coreDataStack.managedObjectContext)
    phoneDeviceType.name = "iPhone"
    let watchDeviceType = DeviceType(entity: deviceTypeEntity, insertInto: coreDataStack.managedObjectContext)
    watchDeviceType.name = "Watch"

    for i in 1...50000 {
        let device = Device(entity: entity, insertInto: coreDataStack.managedObjectContext)
        device.name = "Some Device #\(i)"
        device.deviceType = i % 3 == 0 ? watchDeviceType : phoneDeviceType
    }

    let bob = Person(entity: personEntity, insertInto: coreDataStack.managedObjectContext)
    bob.name = "Bob"
    let jane = Person(entity: personEntity, insertInto: coreDataStack.managedObjectContext)
    jane.name = "Jane"

    coreDataStack.saveMainContext()
  }

    func applicationWillTerminate(_ application: UIApplication) {
        coreDataStack.saveMainContext()
  }
}

